package com.tsingteng.cosfun.ui.message.geneal;


import android.annotation.SuppressLint;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.tsingteng.cosfun.R;
import com.tsingteng.cosfun.app.DialogListener;
import com.tsingteng.cosfun.base.BasePresenterFragment;
import com.tsingteng.cosfun.bean.AttentFansbean;
import com.tsingteng.cosfun.bean.FollowBean;
import com.tsingteng.cosfun.bean.ParagraphComment;
import com.tsingteng.cosfun.bean.PlayCommont;
import com.tsingteng.cosfun.bean.PlayDetailsBean;
import com.tsingteng.cosfun.common.Config;
import com.tsingteng.cosfun.common.Navigate;
import com.tsingteng.cosfun.helper.VideoHelper;
import com.tsingteng.cosfun.ui.cosfun.AtFragment;
import com.tsingteng.cosfun.ui.cosfun.PlayActivity;
import com.tsingteng.cosfun.ui.cosfun.ShareFragment;
import com.tsingteng.cosfun.ui.cosfun.TipOffsActivity;
import com.tsingteng.cosfun.ui.message.geneal.presenter.PlayDetailsContract;
import com.tsingteng.cosfun.ui.message.geneal.presenter.PlayDetailsPresenter;
import com.tsingteng.cosfun.ui.mine.HomeMineFragment;
import com.tsingteng.cosfun.ui.mine.TerminalActivity;
import com.tsingteng.cosfun.utils.DialogUtil;
import com.tsingteng.cosfun.utils.ImageUtils;
import com.tsingteng.cosfun.utils.KeyBoardUtils;
import com.tsingteng.cosfun.utils.LogonUtils;
import com.tsingteng.cosfun.utils.ShareUtils;
import com.tsingteng.cosfun.utils.VideoUtils;
import com.tsingteng.cosfun.widget.MyRecycleView;
import com.tsingteng.cosfun.widget.TitleView;
import com.tsingteng.cosfun.widget.dialog.BottomListDialog;
import com.tsingteng.cosfun.widget.dialog.CommentPlayDialog;
import com.umeng.analytics.MobclickAgent;
import com.umeng.socialize.bean.SHARE_MEDIA;

import java.util.ArrayList;
import java.util.Formattable;
import java.util.List;
import java.util.Objects;

import butterknife.BindView;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;


/**
 * 描述 :
 * 创建人: 肖利.
 * 时间:2018/8/7
 * qq(872179966)
 */

public class PlayDetailFragment extends BasePresenterFragment<PlayDetailsPresenter, PlayDetailsContract.IPlayDetailsView> implements PlayDetailsContract.IPlayDetailsView,
        TitleView.OnTitleClickListener, View.OnClickListener, BottomListDialog.OnClickBottomListListener,
        PlayDetailsAdapter.OnPlayDetailClickListener, ShareFragment.OnShareItemClickLisenter, ShareUtils.ShareListener, DialogListener, TextWatcher {
    @BindView(R.id.tv_title_view)
    TitleView mTitleView;
    @BindView(R.id.rv_details_play)
    MyRecycleView rvDetailsPlay;
    @BindView(R.id.et_comment)
    EditText etComment;
    @BindView(R.id.ll_comment)
    LinearLayout llComment;
    private CircleImageView ivHeader;
    private TextView tvName;
    private TextView tvOperator;
    private ImageView ivMore;
    private RelativeLayout rlGuanZhu;
    private TextView tvContent;
    private ImageView ivFilmDrama;
    private TextView tvCommentNum;
    private TextView tvShareNum;
    private TextView mAdapterNum;
    private TextView tvHistory;
    private String playId;
    private int page = 1;
    private List<String> bottomList = new ArrayList<>();
    private BottomListDialog bottomListDialog;
    private boolean isReply = false;
    private int id;
    private PlayDetailsBean data;
    private int follow_pid;
    private TextView tv_play_details_guan_zhu;
    private LinearLayout ll_play_detail_great;
    private ImageView iv_great;
    private TextView tv_great_num;
    private int profileId;
    private boolean isComment = false;
    public TextView mGreatNum;
    public ImageView mCreat;
    private PlayCommont.CommontList item;
    private ShareFragment shareFragment;
    private LinearLayout mllShoot;
    private RelativeLayout rlMore;
    private ImageView mIvatt;
    private int index = 0;
    private int location = 0;

    public static PlayDetailFragment newInstance(int id, String name) {
        Bundle bundle = new Bundle();
        PlayDetailFragment fragment = new PlayDetailFragment();
        bundle.putInt("playId", id);
        bundle.putString("playName", name);
        fragment.setArguments(bundle);
        return fragment;
    }


    @Override
    protected void getBundle(Bundle bundle) {
        super.getBundle(bundle);
        playId = String.valueOf(bundle.getInt("playId"));
    }


    @Override
    protected void refresh() {
        page = 1;
        mPresenter.getPlayDetailData(playId);
    }

    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart(getResources().getString(R.string.play_detail_fragment));
    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(getResources().getString(R.string.play_detail_fragment));
    }

    @Override
    protected void initData(View rootView) {
        shareFragment = new ShareFragment();
        mTitleView.setOnTitleClickListener(this);
        mTitleView.setIvLeft(R.drawable.back_big_icon);
        mTitleView.setIvRight(R.drawable.more_icon);
        etComment.addTextChangedListener(this);
        mPresenter.getPlayDetailData(playId);
        bottomListDialog = new BottomListDialog(getContext());
        bottomListDialog.setOnClickBottomListListener(this);

        Intent intent = getActivity().getIntent();
        follow_pid = intent.getIntExtra("follow_pid", 0);


    }

    @Override
    protected PlayDetailsPresenter createPresenter() {
        return new PlayDetailsPresenter();
    }

    @Override
    protected View initHeader() {
        View headerView = View.inflate(getContext(), R.layout.view_header_play_details, null);
        ll_play_detail_great = headerView.findViewById(R.id.ll_play_detail_great);
        iv_great = headerView.findViewById(R.id.iv_great);
        tv_great_num = headerView.findViewById(R.id.tv_great_num);
        ivHeader = headerView.findViewById(R.id.iv_header);
        tv_play_details_guan_zhu = headerView.findViewById(R.id.tv_play_details_guan_zhu);
        tvName = headerView.findViewById(R.id.tv_name);
        tvOperator = headerView.findViewById(R.id.tv_operator);
        mllShoot = headerView.findViewById(R.id.ll_shoot_num);
        rlGuanZhu = headerView.findViewById(R.id.rl_guan_zhu);
        tvContent = headerView.findViewById(R.id.tv_content);
        ivMore = headerView.findViewById(R.id.iv_more);
        rlMore = headerView.findViewById(R.id.rl_more);
        ivFilmDrama = headerView.findViewById(R.id.iv_film_drama);
        mIvatt = headerView.findViewById(R.id.iv_guan_zhu);
        tvCommentNum = headerView.findViewById(R.id.tv_comment_num);
        tvShareNum = headerView.findViewById(R.id.tv_share_num);
        tvHistory = headerView.findViewById(R.id.tv_history);
        headerView.findViewById(R.id.ll_share).setOnClickListener(this);
        mAdapterNum = headerView.findViewById(R.id.tv_comment_num_adapter);
        ivMore.setOnClickListener(this);
        rlMore.setOnClickListener(this);
        rlGuanZhu.setOnClickListener(this);
        ivFilmDrama.setOnClickListener(this);
        mllShoot.setOnClickListener(this);
        ll_play_detail_great.setOnClickListener(this);
        ivHeader.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int tag;
                if (data.getRelationType() == -1) {
                    tag = 0;
                } else {
                    tag = 1;
                }
                int profileId = data.getProfileId();
                Bundle bundle = new Bundle();
                bundle.putInt("tag", tag);
                bundle.putInt("user_id", profileId);
                TerminalActivity.showFragment(getContext(), HomeMineFragment.class, bundle);
            }
        });
        return headerView;
    }

    @Override
    protected MyRecycleView createRecycleView() {
        return rvDetailsPlay;
    }

    @Override
    protected BaseQuickAdapter createAdapter() {
        PlayDetailsAdapter playDetailsAdapter = new PlayDetailsAdapter();
        playDetailsAdapter.setOnPlayDetailClickListener(this);
        return playDetailsAdapter;
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        etComment.setText("");
        PlayCommont.CommontList commontList = (PlayCommont.CommontList) adapter.getData().get(position);
        profileId = commontList.getProfileId();
        KeyBoardUtils.searchPoint(etComment);
        this.id = commontList.getCommentId();
        etComment.setSelection(etComment.getText().toString().trim().length());
        isReply = true;
        String content = "";
        showCommentDialog(playId,null);
    }

    @Override
    public void onLoadMoreRequested() {
        page++;
        mPresenter.getPlayDetailCommontListData(playId, page, Config.PAGE_SIZE);

    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_play_details;
    }

    @Override
    public void showPlayDetailsData(PlayDetailsBean data) {
        rvDetailsPlay.refreshComplete();
        initViewData(data);
        if (page == 1) mPresenter.getPlayDetailCommontListData(playId, page, Config.PAGE_SIZE);
    }

    @Override
    public void showPlayDetailCommontListData(PlayCommont data) {
        if (data == null) {
            mAdapter.loadMoreComplete();
        } else {
            mAdapter.loadMoreEnd();
        }
        rvDetailsPlay.refreshComplete();
        mAdapter.addData(data.getData());
    }

    @Override
    public void ShowNotLiketResult(String status) {
        showToast("已经设置为不喜欢");
        if (bottomListDialog != null) {
            bottomListDialog.dissMiss();
        }
    }


    /**
     * 确认弹窗
     */
    private void confirmDialog() {
        @SuppressLint({"StringFormatInvalid", "LocalSuppress"})
        String content = Objects.requireNonNull(getActivity()).getResources().getString(R.string.comment_black, data.getNickName());
        DialogUtil.getContentDialog(getActivity(), content);
    }

    /**
     * 拉黑别人
     */
    private void confirmBlackDialog(String msg) {
        @SuppressLint({"StringFormatInvalid", "LocalSuppress"})
        String content = getResources().getString(R.string.comment_handle, data.getNickName());
        DialogUtil.getContentCommentDialog(getActivity(), content, data.getProfileId(), this);
    }

    @Override
    public void showAddCommentResult(ParagraphComment data) {
        mAdapter.addData(0, data.getParagraphComment());

    }

    @Override
    public void showDelResult(String status) {
        if (bottomListDialog != null) {
            bottomListDialog.dissMiss();
        }
        if (null == getActivity()){
            return;
        }
        getActivity().finish();
    }

    @Override
    public void getFollowResult(FollowBean followBean) {
        int relationType = followBean.getRelationType();
        if (relationType == 0) {
            tv_play_details_guan_zhu.setText("关注");
            VideoUtils.handelUserGuznZhu(String.valueOf(data.getProfileId()), "0");
            mIvatt.setBackground(getActivity().getResources().getDrawable(R.drawable.shape_bg_white));
            tv_play_details_guan_zhu.setTextColor(getActivity().getResources().getColor(R.color.black));
        } else if (relationType == 1) {
            tv_play_details_guan_zhu.setText("已关注");
            VideoUtils.handelUserGuznZhu(String.valueOf(data.getProfileId()), "1");
            mIvatt.setBackground(getActivity().getResources().getDrawable(R.drawable.shape_trank_bg));
            tv_play_details_guan_zhu.setTextColor(getActivity().getResources().getColor(R.color.white));
        } else if (relationType == 2) {
            tv_play_details_guan_zhu.setText("相互关注");
            mIvatt.setBackground(getActivity().getResources().getDrawable(R.drawable.shape_pink_bg));
            tv_play_details_guan_zhu.setTextColor(getActivity().getResources().getColor(R.color.color_found));
        }
        data.setRelationType(relationType);


    }


    @Override
    public void showPraiseResult(Integer data1) {
        if (isComment) {
            if (data1 == 1) {
                item.setPraiseStatus(1);
                int num = Integer.valueOf(item.getpCount()) + 1;
                item.setpCount(String.valueOf(num));
                mGreatNum.setText(String.valueOf(num));
                showToast("点赞成功!");
                mCreat.setImageDrawable(getResources().getDrawable(R.drawable.great_pink_small_icon));
            } else {
                int num = Integer.valueOf(item.getpCount()) - 1;
                item.setpCount(String.valueOf(num));
                mGreatNum.setText(String.valueOf(num));
                mCreat.setImageDrawable(getResources().getDrawable(R.drawable.great_small_icon));
                showToast("取消点赞成功!!");
                item.setPraiseStatus(0);
            }
            isComment = false;
            return;
        }
        if (data1 == 1) {
            data.setPraiseStatus(1);
            int num = Integer.valueOf(data.getPraiseCount()) + 1;
            data.setPraiseCount(String.valueOf(num));
            tv_great_num.setText(String.valueOf(num));
            showToast("点赞成功!");
            iv_great.setImageDrawable(getResources().getDrawable(R.drawable.great_pink_icon));
        } else {
            int num = Integer.valueOf(data.getPraiseCount()) - 1;
            data.setPraiseCount(String.valueOf(num));
            tv_great_num.setText(String.valueOf(num));
            iv_great.setImageDrawable(getResources().getDrawable(R.drawable.great_icon));
            showToast("取消点赞成功!!");
            data.setPraiseStatus(0);
        }
    }

    @Override
    public void showCancelPullBlack(int data) {
        if (1 == data) {
            showToast(getResources().getString(R.string.cancel_black_success));
        }
    }

    @Override
    public void showDialog(int code) {
        if (50072 == code) {
            confirmDialog();
        } else if (50073 == code) {
            confirmBlackDialog("50073");
        }
    }

    private void initViewData(PlayDetailsBean data) {
        this.data = data;
        mTitleView.setTitle(data.getNickName() + "的便当");
        ImageUtils.LoadImage(getContext(), data.getImage(), ivHeader);
        setText(tvName, data.getNickName());
        setText(tvOperator, data.getOperatorLabel());
        setText(tvContent, data.getContent());
        setText(tv_great_num, data.getPraiseCount());
        setText(tvCommentNum, String.valueOf(data.getCommentCount()));
        setText(tvShareNum, String.valueOf(data.getForwardCount()));
        setText(tvShareNum, String.valueOf(data.getForwardCount()));
        setText(tvHistory, data.getVideoCount());
        setText(mAdapterNum, "评论 " + String.valueOf(data.getCommentCount()));
        if (data.getPraiseStatus() == 0) {
            iv_great.setImageDrawable(mContent.getResources().getDrawable(R.drawable.great_icon));
        } else {
            iv_great.setImageDrawable(mContent.getResources().getDrawable(R.drawable.great_pink_icon));
        }

        if (data.getRelationType() == 0) {
            tv_play_details_guan_zhu.setText("关注");
            mIvatt.setBackground(getActivity().getResources().getDrawable(R.drawable.shape_bg_white));
            tv_play_details_guan_zhu.setTextColor(getActivity().getResources().getColor(R.color.black));
        } else if (data.getRelationType() == 1) {
            tv_play_details_guan_zhu.setText("已关注");
            mIvatt.setBackground(getActivity().getResources().getDrawable(R.drawable.shape_trank_bg));
            tv_play_details_guan_zhu.setTextColor(getActivity().getResources().getColor(R.color.white));
        } else if (data.getRelationType() == 2) {
            tv_play_details_guan_zhu.setText("互相关注");
            mIvatt.setBackground(getActivity().getResources().getDrawable(R.drawable.shape_pink_bg));
            tv_play_details_guan_zhu.setTextColor(getActivity().getResources().getColor(R.color.color_found));
        } else if (data.getRelationType() == -1) {
            rlGuanZhu.setVisibility(View.INVISIBLE);
        }
    }

    public void setText(TextView textView, String text) {
        if (textView == null || TextUtils.isEmpty(text)) return;
        textView.setText(text);
    }


    @OnClick({R.id.et_comment, R.id.iv_at})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.et_comment:
                if (TextUtils.isEmpty(etComment.getText().toString())) {
                    etComment.setText("");
                    isReply = false;
                }
                showCommentDialog(playId,null);

                break;
            case R.id.iv_at:

               AtFragment atFragment = AtFragment.newInstance();
                atFragment.setOnItemSelectLisenter(new AtFragment.OnItemSelectLisenter() {
                    @Override
                    public void selected(AttentFansbean.Data data) {
                        showCommentDialog(playId,data);
                        atFragment.dismiss();
                    }
                });
                if (null ==getActivity()){
                    return;
                }
                atFragment.show(getActivity().getSupportFragmentManager(), "myFragment");
                break;
        }
    }

    @Override
    public void onLeft() {
        getActivity().finish();
    }

    @Override
    public void onRight() {
        bottomList.clear();
        if (data.getProfileId() == LogonUtils.getProFildId()) {
            bottomList.add("删除");
        } else {
            bottomList.add("举报");
            bottomList.add("不喜欢");
        }
        bottomListDialog.setList(bottomList);
        bottomListDialog.show();
    }

    @Override
    public void onRight2() {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_more:
                bottomList.clear();
                if (data.getProfileId() == LogonUtils.getProFildId()) {
                    bottomList.add("删除");
                } else {
                    bottomList.add("举报");
                    bottomList.add("不喜欢");
                }
                bottomListDialog.setList(bottomList);
                bottomListDialog.show();
                break;
            case R.id.ll_share:
                if (shareFragment == null) shareFragment = new ShareFragment();
                shareFragment.setLisenter(this);
                shareFragment.setTag("play");
                shareFragment.show(getActivity().getSupportFragmentManager(), "playDetailFragment");
                break;
            case R.id.rl_guan_zhu:
                if (data.getRelationType() == 0) {
                    mPresenter.loginFollowFans(follow_pid + "");
                } else if (data.getRelationType() == 1) {
                    mPresenter.loginNoFollow(follow_pid + "");
                } else if (data.getRelationType() == 2) {
                    mPresenter.loginNoFollow(follow_pid + "");
                }
                break;
            case R.id.ll_play_detail_great:
                if (data.getPraiseStatus() == 1) {
                    mPresenter.getPraiseOrNotData("-1", String.valueOf(data.getId()), "0");
                } else {
                    mPresenter.getPraiseOrNotData("1", String.valueOf(data.getId()), "0");
                }
                break;

            case R.id.iv_film_drama:
                VideoHelper.getIntence().starVideoShootToPlay(getActivity(), data.getId());
                break;

            case R.id.ll_shoot_num:
                if (null == data){
                    return;
                }
                Intent intent = new Intent(getContext(), PlayActivity.class);
                intent.putExtra("type", 1);
                intent.putExtra("id", data.getId());
                intent.putExtra("position", 0);
                startActivity(intent);
                break;
        }
    }


    @Override
    public void onClickItem(BaseQuickAdapter adapter, View view, int position, List<String> list) {
        switch (list.get(position)) {
            case "举报":
                int tag = 2;
                Navigate.startReportList(getContext(), 1, profileId);
                bottomListDialog.dissMiss();
                break;
            case "不喜欢":
                mPresenter.getAddNotLikePlay(playId);
                bottomListDialog.dissMiss();
                break;
            case "删除":
                new AlertDialog.Builder(getContext()).setTitle("提示").setMessage("确定删除本便当么？").setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        mPresenter.getDelPlay(playId);
                    }
                }).setNegativeButton("取消", null).create().show();
                bottomListDialog.dissMiss();
                break;
        }
    }

    @Override
    public void onClickBottom() {
        if (bottomListDialog != null) {
            bottomListDialog.dissMiss();
        }
    }

    @Override
    public void onPraiseClick(PlayCommont.CommontList item, ImageView mCreat, TextView mGreatNum) {
        this.mCreat = mCreat;
        this.mGreatNum = mGreatNum;
        this.item = item;
        isComment = true;
        if (item.getPraiseStatus() == 1) {
            mPresenter.getPraiseOrNotData("-1", String.valueOf(item.getCommentId()), "1");
        } else {
            mPresenter.getPraiseOrNotData("1", String.valueOf(item.getCommentId()), "1");
        }
    }

    @Override
    public void onUserClick(String userId) {
        Bundle bundle = new Bundle();
        bundle.putInt("user_id", Integer.parseInt(userId));
        bundle.putInt("tag", 1);
        TerminalActivity.showFragment(getActivity(), HomeMineFragment.class, bundle);
    }

    @Override
    public void share(SHARE_MEDIA share_media, int type) {
        showLoading("正在分享...");
        ShareUtils.getIntance().sharePlay(getActivity(), share_media, String.valueOf(data.getId()), data.getNickName(), data.getContent(), data.getImage(), this);
    }

    @Override
    public void other(int type) {
        switch (type) {
            case 1://复制链接
                ClipboardManager cm = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
                // 将文本内容放到系统剪贴板里。
                String path = "";
                ClipData myClip = ClipData.newPlainText("text", path);
                cm.setPrimaryClip(myClip);
                Toast.makeText(getActivity(), "链接已经复制到剪切板", Toast.LENGTH_SHORT).show();
                break;
            case 3://不感兴趣
                showToast("不感兴趣");
//                mPresenter.getLoseInterest(opusBean.getId() + "", System.currentTimeMillis() + "");
                break;
            case 4:
                Toast.makeText(getActivity(), "举报", Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(getActivity(), TipOffsActivity.class);
                startActivity(intent);
                break;
        }
    }

    @Override
    public void onShareFinish() {
        hideLoading();
    }

    @Override
    public void onShareSuccess() {
        hideLoading();
        data.setForwardCount(String.valueOf(Integer.valueOf(data.getForwardCount()) + 1));
        tvShareNum.setText(data.getForwardCount());
    }

    @Override
    public void clickDialog(long workId) {
        mPresenter.getCancelPullBlack(workId);
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        index = s.length();
        location = etComment.getSelectionStart();
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
//        if (index != s.toString().length()) {
//            String input = s.toString();
//            SpannableString msp = KeywordUtil.matcherAtTxt(Color.parseColor("#42DAD7"), input, atList);
//            etComment.setText(msp);
//            etComment.setSelection(etComment.getText().toString().length());
//        }
//        if (etComment.length() == 200) {
//            Toast.makeText(getActivity(), getResources().getString(R.string.message_limit), Toast.LENGTH_LONG).show();
//        }
    }

    private void showCommentDialog(String playId, AttentFansbean.Data data) {
        CommentPlayDialog dialog = new CommentPlayDialog(playId, data, new CommentPlayDialog.CommentPlayDialogListener() {
            @Override
            public void commSuccess(String commStr) {
                if (isReply) {
                    mPresenter.getAddPlayComment(playId, "1", commStr, String.valueOf(id));
                } else {
                    mPresenter.getAddPlayComment(playId, "0", commStr, null);
                }
            }
        });
        dialog.show(getActivity().getSupportFragmentManager(), "comment");
    }
}
